import { useRequest } from '@umijs/max';
import { TablePaginationConfig, TableProps } from 'antd';
import { useEffect, useState } from 'react';

export interface FormatProps {
  data: {
    records: any[];
    total: number;
  };
}
export interface OptionsType {
  form?: any;
  defaultPageParams?: {
    pageNum: number;
    pageSize: number;
  };
  formatResult?: (res: any) => FormatProps;
}
export interface TablePropsType {
  dataSource: TableProps['dataSource'];
  loading: TableProps['loading'];
  pagination: TablePaginationConfig;
  scroll: TableProps['scroll'];
}
const useRequestTable = (
  fetchFun: (params: any, formData: any) => Promise<any>,
  options: OptionsType,
) => {
  const { form, defaultPageParams, formatResult, ...restOptions } =
    options || {};

  const [pageNum, setPageNum] = useState(defaultPageParams?.pageNum || 1);
  const [pageSize, setPageSize] = useState(defaultPageParams?.pageSize || 10);

  const { data, loading, run }: any = useRequest(
    async (): Promise<any> => {
      let formData: any = form && form?.getFieldsValue(true);
      const res = await fetchFun({ pageSize, pageNum, }, formData);
      if (formatResult && typeof formatResult === 'function') {
        return formatResult(res);
      }
      return {
        data: {
          records: res?.data?.records || res?.data || [],
          total: res?.data?.total || res?.data?.length || 0,
        },
      };
    },
    {
      refreshDeps: [pageSize, pageNum],
      // loadingDelay: 10000,
      ...restOptions,
    },
  );
  // console.log(data);
  useEffect(() => {
    // console.log(data, 'useRequestTable-data');
    //  useRequest 固定接收的返回数据需要有data字段，作为请求的结果数据
  }, [data]);

  const tableProps: TablePropsType = {
    dataSource: data?.records || [],
    loading,
    pagination: {
      total: data?.total,
      current: pageNum,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      size: 'small',
      onChange: (page: number, pageSize: number) => {
        setPageNum(page);
        setPageSize(pageSize);
      },
      showTotal: (total: number) =>
        `共${total || 0}条记录 第${pageNum}/${Math.ceil(
          total || 0 / pageSize,
        )}页`,
    },
    scroll: {
      x: '1000px',
    },
  };

  let reset = () => {
    setPageNum(1);
    setPageSize(10);
    form.resetFields();
    run();
  };

  return {
    tableProps,
    search: {
      submit: run,
      reset,
    },
  };
};

export default useRequestTable;

// import { useCallback, useState } from 'react';
// import { useRequest } from 'umi';

// /**
//  *
//  * @param {*} request - 请求函数
//  * @param {*} options - 参数
//  */
// const useTableRequest = (
//   request,
//   { form, dataSource = [], total = 0, useRequestConfig = {} },
// ) => {
//   const [pageNum, setPageNum] = useState(1);
//   const [pageSize, setPageSize] = useState(10);

//   const { loading, run, data } = useRequest(
//     () => request({ pageNum, pageSize }),
//     {
//       refreshDeps: [pageNum, pageSize],
//       ...useRequestConfig,
//     },
//   );

//   // const { records, total } = data || {};
//   const reset = useCallback(() => {
//     setPageNum(1);
//     form.resetFields();
//     run();
//   }, []);

//   const tableProps = {
//     loading,
//     pagination: {
//       current: pageNum,
//       pageSize,
//       showQuickJumper: true,
//       showSizeChanger: true,
//       onChange: (page, pageSize) => {
//         setPageNum(page);
//         setPageSize(pageSize);
//       },
//       total,
//       showTotal: () =>
//         `共${total}条记录 第${pageNum}/${Math.ceil(total / pageSize)}页`,
//     },
//     dataSource,
//   };

//   return {
//     tableProps,
//     search: {
//       reset,
//       submit: run,
//     },
//   };
// };

// export default useTableRequest;
